<template>
    <div>
      <el-button style="margin-bottom: 15px;" type="primary" :icon="Edit" @click="onDialog('新建',null)">
        添加分类
      </el-button>
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="c_id"
        border
        default-expand-all
      >
        <el-table-column prop="c_name" label="类别名称" sortable />
        <el-table-column prop="c_info" label="类别描述" sortable />
        <el-table-column prop="level" label="分类所处等级" sortable />
        <el-table-column label="操作">
        <template #default="scope">
            <el-button type="warning" :icon="Edit" circle  @click="onDialog('修改',scope)"/>
            <el-button type="danger" :icon="Delete" circle @click="onDdelete(scope.row)"/>
        </template>
        </el-table-column>
      </el-table>
    </div>
  <dialogv :showDia = "showDia" @showDiaf="showDiaf" :title="title" :nid="data.nid"></dialogv>
  </template>
  <script lang="ts" setup>
  import { classListApi, classDeleteApi } from "../composables/http";
  import { Delete, Edit } from '@element-plus/icons-vue'
  import { onMounted, reactive,toRefs, ref } from "vue";
  import dialogv from "../components/fldialog.vue";
  import { ElMessage  } from 'element-plus'

  const title = ref("新建")
  onMounted(()=>{
    dataList()
  })
  const data = reactive<{
    tableData:API.classListData[]
    showDia:boolean,
    nid:number
  }>({
    tableData:[],
    showDia:false,
    nid:0
  });
  const dataList = async()=>{
    const d = await classListApi()
    if (d.code == 200){
        data.tableData = []
        d.data.forEach((e) =>{
          const d = {
                "c_id":e.pk,
                "c_name": e.fields.c_name,
                "c_info": e.fields.c_info,
                "c_parent_id": e.fields.c_parent_id,
                "level": e.fields.level,
                "children":[]
          }
          data.tableData.push(d)
        })
        const treeData = listToTreeData(data.tableData, 0) // 调用方法
        data.tableData = treeData
    }
  }
  const listToTreeData = (list:any, rootValue:number) => {
    var arr:any = []
    list.forEach((item:any) => {
        if (item.c_parent_id === rootValue) {
            const children = listToTreeData(list, item.c_id)
            if (children.length) {
                item.children = children
            }
            arr.push(item)
        }
    })
    return arr
  }
  const onDialog = (v:string, scope:any)=>{
    title.value = v
    if (scope != null) {
      data.nid = scope.row.c_id
    }
    data.showDia = true
  }
  const onDdelete = async(row:any)=>{
    const d = await classDeleteApi(row.c_id)
    if (d.code == 200){
      ElMessage.error("删除成功!")
      dataList()
    }
  }
  const showDiaf = (val:boolean)=>{
    data.showDia = val
    // console.log(data.showDia);
    dataList()
  }
  const { tableData,showDia } = toRefs(data)
  </script>